#include "declares.h"
#include "log.h"
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

static pid_t pid = -1;

pid_t start_diag()
{
    switch (pid = fork())
    {
    case -1:
        return -1;
    case 0:
        break;
    default:
        return pid;
    }

    time_t _tm;
    char buff[64];
    _tm = time(NULL);
    struct tm *tmp = localtime(&_tm);
    snprintf(buff, 64, "log_%02d:%02d:%02d", tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
    DEBUG("log dir is /log/%s", buff);
    mkdir(buff, S_IRWXU | S_IRWXG | S_IRWXO);
    chdir(buff);

    memset(buff, 64, 0);
    snprintf(buff, 64, "%s/bin/diag", home_dir);
    DEBUG("start %s", buff);

    if (execl(buff, "diag", "log", NULL) < 0)
    {
        DEBUG("start diag failed");
        perror("execl");
        exit(EXIT_FAILURE);
    }
}

void close_diag()
{
    DEBUG("diag is running");
    DEBUG("kill diag, pid is %d", pid);

    kill(pid, SIGINT);

    DEBUG("waiting diag exit");
    int code;
    waitpid(pid, &code, 0);

    DEBUG("diag returned %d", code);
}